package com.aida.evil.eda.Answer;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Data.UserData;
import com.aida.evil.eda.Toast.CustomSuperActivityToast;
import com.aida.evil.eda.Volley.VolleyHandler;
import com.aida.evil.eda.Volley.VolleyHttpRequest;
import com.aida.evil.eda.Window.CustomDialog;
import com.github.johnpersano.supertoasts.SuperToast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/********************************************
 * 工程名：Aida
 * 包名：com.aida.evil.eda.Answer
 * 时间：16-4-30 下午9:41
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：答题界面
 ********************************************/
public class AnswerActivity extends AppCompatActivity
{
    private final static String ITEMURL = "http://" + NetworkData.ServiceIP + "/AnswerItem?";

    private Toolbar toolbar;/*顶部栏*/
    private TabLayout tabLayout;/*ViewPager的顶部指示器*/
    public static ViewPager viewPager;
    private Adapter adapter;
    private ProgressBar progressBar;
    private LinearLayout linearLayout;

    private String itemTitle;/*题目集的标题*/
    public static int itemID;/*题目集的ID*/
    private int position;/*题目在listview的坐标*/
    private int size;/*题目集大小*/
    private boolean b = true;/*如果题目集有题目，退出时提示，如果没有，则退出不提示*/

    private ArrayList<ItemBean> list = new ArrayList<>();/*题目集内容*/
    private ArrayList<String> tabTitleList = new ArrayList<>();/*指示器的标题集合*/
    private ArrayList<Fragment> fragmentList = new ArrayList<>();/*fragment集合*/


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.answer);

        initView();/*初始化控件*/
        getIntentDate();/*获得从主界面传来的数据*/
        toNetWork();/*初始化数据*/
    }

    /**
     * 初始化控件
     */
    private void initView()
    {
        toolbar = (Toolbar) findViewById(R.id.answer_toolbar);
        tabLayout = (TabLayout) findViewById(R.id.answer_tabLayout);
        viewPager = (ViewPager) findViewById(R.id.answer_viewPager);
        progressBar = (ProgressBar) findViewById(R.id.answer_progressBar);
        linearLayout = (LinearLayout) findViewById(R.id.answer_linearLayout);
    }

    /**
     * 初始化数据
     */
    private void initData()
    {
        progressBar.setVisibility(View.GONE);
        linearLayout.setVisibility(View.VISIBLE);
        if (size > 0)
        {
            for (int i = 0; i < size; i++)
            {
                tabTitleList.add("试题" + (i + 1));
                ItemBean itemBean = list.get(i);

                fragmentList.add(AnswerItemFragment.newInstance(itemID, position, i, size
                        , itemBean.id, itemBean.imgPath, itemBean.question, itemBean.yes, itemBean.no
                        , itemBean.briefUrl, itemBean.flow));
            }

            setToolBar();/*设置ToolBar*/
            setViewPager();/*设置ViewPager*/
        }
        else
        {
            b = false;
            CustomSuperActivityToast.makeText(this, "暂时没有内容，请稍后刷新重试！", "退出", new SuperToast.OnClickListener()
            {
                @Override
                public void onClick(View view, Parcelable token)
                {
                    if (viewPager != null)
                        viewPager.removeAllViews();
                    finish();
                }
            }).setDuration(Integer.MAX_VALUE).setButtonIcon(SuperToast.Icon.Light.EXIT).show();
        }
    }


    /**
     * 网络加载
     */
    private void toNetWork()
    {
        progressBar.setVisibility(View.VISIBLE);
        VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
        {
            ItemList itemList = null;

            @Override
            public void reqSuccess(String response)
            {
                progressBar.setVisibility(View.GONE);
                if (response.equals("MORE"))
                {
                    final CustomDialog.Builder builder = new CustomDialog.Builder(AnswerActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("您今天答题数目已经超过上限，\n请您明天再来哦！");
                    builder.setMessageTextSize(20);
                    builder.setPositiveButton("退出", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            builder.dismiss();
                            finish();
                        }
                    });
                    builder.show();
                }
                else
                {

                /*解析Json*/
                    {
                        Type type = new TypeToken<ItemList>()
                        {
                        }.getType();
                        itemList = new Gson().fromJson(response, type);
                    }
                /*解析数据*/
                    {
                        itemID = itemList.itemID;
                        size = itemList.listSize;
                        list = itemList.list;
                    }
                    initData();/*初始化数据*/
                    //refreshHandler.sendEmptyMessage(0);
                }
            }

            @Override
            public void reqError(String error)
            {
                progressBar.setVisibility(View.INVISIBLE);

                CustomSuperActivityToast.makeText(AnswerActivity.this,
                        "加载失败，请重试", "重试", new SuperToast.OnClickListener()
                        {
                            @Override
                            public void onClick(View view, Parcelable token)
                            {
                                toNetWork();/*重新加载网络*/
                            }
                        }).show();
            }
        };
        // VolleyHttpRequest.String_request(ITEMURL + "itemID=" + itemID, stringVolleyHandler);
        Map<String, String> map = new HashMap<>();
        map.put("userPhoneNum", UserData.DATA_PHONENUM + "");
        map.put("itemID", itemID + "");
        VolleyHttpRequest.String_request(ITEMURL, map, stringVolleyHandler);
    }

    /**
     * 获得从主界面传来的数据
     * 包含ItemTitle，ItemID
     */

    private void getIntentDate()
    {
        itemTitle = getIntent().getStringExtra("itemTitle");
        itemID = getIntent().getIntExtra("itemID", 0);
        position = getIntent().getIntExtra("position", 0);
    }

    /**
     * 设置ToolBar
     */
    private void setToolBar()
    {
        //toolbar.setTitle("答题界面");
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    /**
     * toolbar返回键监听
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if (item.getItemId() == android.R.id.home)
        {
            /*if (b)
                new Answer.showDialog(this)
                {
                    @Override
                    public void clear()
                    {
                        viewPager.removeAllViews();
                    }
                }.show();
            else*/
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 设置ViewPager
     */
    private void setViewPager()
    {
        adapter = new Adapter(getSupportFragmentManager());
        for (int i = 0; i < tabTitleList.size(); i++)
        {
            tabLayout.addTab(tabLayout.newTab().setText(tabTitleList.get(i)));
        }

        viewPager.setAdapter(adapter);

        LinearLayout.LayoutParams layoutParams = new LinearLayout
                .LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                , ViewGroup.LayoutParams.WRAP_CONTENT);

        /*这里应该去计算屏幕宽度，然后根据宽度来设定多少个Tab才能去铺满屏幕，超过的话用滚动  ！！！以后执行*/
        if (tabTitleList.size() < 5)
        {
            tabLayout.setTabMode(TabLayout.MODE_FIXED);/*设置tab模式，当前为系统默认模式*/
            tabLayout.setLayoutParams(layoutParams);
        }
        else tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);/*设置tab模式，当前为滚动模式*/
        tabLayout.setupWithViewPager(viewPager);/*把tabLayout和viewPager进行关联*/

        tabLayout.setTabsFromPagerAdapter(adapter);
    }

    /**
     * ViewPager的适配器
     */
    private class Adapter extends FragmentStatePagerAdapter
    {
        public Adapter(FragmentManager fm)
        {
            super(fm);
        }

        @Override
        public Fragment getItem(int position)
        {
            return fragmentList.get(position);
        }

        @Override
        public int getCount()
        {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position)
        {
            return tabTitleList.get(position);
        }
    }

    @Override
    public void onBackPressed()
    {
        //super.onBackPressed();
        /*if (b)
            new Answer.showDialog(this)
            {
                @Override
                public void clear()
                {
                    viewPager.removeAllViews();
                }
            }.show();
        else*/
        finish();
    }

    public class ItemList
    {
        private int itemID;//题目集的id
        private int listSize;//题目集的大小
        private ArrayList<ItemBean> list;//试题内容
    }

    public class ItemBean
    {
        private String id;//试题id
        private String imgPath;//试题图片地址
        private String question;//试题问题
        private String yes;//试题正确答案
        private String[] no;//试题错误答案
        private String briefUrl;//试题详细内容的html地址
        private int flow;//完成试题能够获得的流量
    }

/*    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        new Answer.showDialog(this)
        {
            @Override
            public void clear()
            {
                if (list != null)
                    list.clear();
                if (fragmentList != null)
                    fragmentList.clear();
                if (tabTitleList != null)
                    tabTitleList.clear();
                if (viewPager != null)
                    viewPager.removeAllViews();
            }
        }.toNetWork();
    }*/
}

















